package com.liyongjian.xhban.api;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liyongjian.xhban.dal.UserFriendConfirmRepository;
import com.liyongjian.xhban.dal.UserFriendRepository;
import com.liyongjian.xhban.dal.UserMsgRepository;
import com.liyongjian.xhban.dal.UserRepository;
import com.liyongjian.xhban.dto.AjaxResponse;
import com.liyongjian.xhban.dto.SessionUser;
import com.liyongjian.xhban.exception.XHBanException;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.UserFriend;
import com.liyongjian.xhban.model.UserFriendConfirm;
import com.liyongjian.xhban.model.emumm.LiveDieState;
import com.liyongjian.xhban.model.emumm.UserFriendState;
import com.liyongjian.xhban.utils.MapUtils;


@Controller
@RequestMapping("/api/friend")
public class FriendController extends BaseController {
    @Autowired
    private UserFriendRepository userFriendRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserFriendConfirmRepository userFriendConfirmRepository;
    @Autowired
    private UserMsgRepository userMsgRepository;

    @ResponseBody
    @RequestMapping(path = "my/list", method = RequestMethod.GET)
    public AjaxResponse my_list(HttpServletRequest request, String token,
            HttpServletResponse response,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable)
                    throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Page<UserFriend> users = userFriendRepository.findFriendByUserId(su.id, pageable);
        return ajax.setObj(users.map(new Converter<UserFriend, Map<String, Object>>() {
            public Map<String, Object> convert(UserFriend source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.friendUserId);
                map.put("id", user.id);
                map.put("photo", user.photo);
                map.put("nickName", user.nickName);
                return map;
            }
        }));
    }


    @ResponseBody
    @RequestMapping(path = "my/req", method = RequestMethod.GET)
    public AjaxResponse my_req(HttpServletRequest request, String token,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Page<UserFriendConfirm> users =
                userFriendConfirmRepository.findFriendByUserId(su.id, pageable);
        return ajax.setObj(users.map(new Converter<UserFriendConfirm, Map<String, Object>>() {
            public Map<String, Object> convert(UserFriendConfirm source) {
                Map<String, Object> map = MapUtils.convert(source);
                User user = userRepository.findOne(source.friendUserId);
                map.put("photo", user.photo);
                map.put("nickName", user.nickName);
                return map;
            }
        }));
    }



    @ResponseBody
    @RequestMapping(path = "find", method = RequestMethod.GET)
    public AjaxResponse find(HttpServletRequest request, String token, String key,
            @PageableDefault(sort = {"id"}, direction = Direction.DESC) Pageable pageable) {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        Long id = StringUtils.isNumeric(key) ? Long.valueOf(key) : null;
        Page<User> users = userRepository.findByUserNick(key, id, pageable);
        return ajax.setObj(users.map(new Converter<User, Map<String, Object>>() {
            public Map<String, Object> convert(User source) {
                Map<String, Object> map = MapUtils.convert(source);
                return map;
            }
        }));
    }

    @Transactional
    @ResponseBody
    @RequestMapping(path = "add", method = RequestMethod.POST)
    public AjaxResponse add(HttpServletRequest request, String token, Long userId,
            UserFriendState state, HttpServletResponse response) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = this.getCurrentUser(token);
        User user = userRepository.findByIdAndState(userId, LiveDieState.LIVE);
        if (user == null || user.id == su.id.longValue()) {
            throw new XHBanException("用户编号错误");
        }
        UserFriend uf = userFriendRepository.findByUserIdAndFriendUserId(su.id, userId);
        if (uf == null) {
            uf = new UserFriend();
            uf.userId = su.id;
            uf.friendUserId = userId;
            uf.state = UserFriendState.LIVE;
            userFriendRepository.save(uf);
        } else {
            if (state != null) {
                uf.state = state;
                userFriendRepository.save(uf);
            }

        }

        UserFriend uf2 = userFriendRepository.findByUserIdAndFriendUserId(userId, su.id);
        if (uf2 == null) {
            uf2 = new UserFriend();
            uf2.userId = userId;
            uf2.friendUserId = su.id;
            uf2.state = UserFriendState.DD;
            userFriendRepository.save(uf2);
        }

        return ajax;
    }

}
